/**
 * 
 */
package com.techq.weibo.auth.imp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;

import com.techq.weibo.auth.Auth;
import com.techq.weibo.meta.User;
import com.techq.weibo.robot.CrawlRobot;
import com.techq.weibo.share.exception.ShareException;

/**
 * @author tassemble@gmail.com 2011-8-3
 */
public class SinaWeiboAuth implements Auth {

	Logger logger = Logger.getLogger(SinaWeiboAuth.class);
	static List<NameValuePair> qparams;
	static HttpPost post;
	static {
		qparams = new ArrayList<NameValuePair>();
		qparams.add(new BasicNameValuePair("entry", "miniblog"));
		qparams.add(new BasicNameValuePair("gateway", "1"));
		qparams.add(new BasicNameValuePair("from", ""));
		qparams.add(new BasicNameValuePair("savestate", "0"));
		qparams.add(new BasicNameValuePair("useticket", "1"));
		qparams.add(new BasicNameValuePair("ssosimplelogin", "1"));
		qparams.add(new BasicNameValuePair("service", "miniblog"));
		qparams.add(new BasicNameValuePair("encoding", "utf-8"));
		qparams.add(new BasicNameValuePair(
						"url",
						"http://weibo.com/ajaxlogin.php?framelogin=1&"
								+ "callback=parent.sinaSSOController.feedBackUrlCallBack"));
		qparams.add(new BasicNameValuePair("returntype", "META"));

		post = new HttpPost(
				"http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.3.14)");
		post.setHeader("Host", "login.sina.com.cn");
		post.setHeader("User-Agent",
						"Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0");
		post.setHeader("Referer", "http://weibo.com/");
		post.setHeader("Content-Type", "application/x-www-form-urlencoded");
		

	}

	/**
	 * 
	 */
	public SinaWeiboAuth() {
		// TODO Auto-generated constructor stub
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.techq.weibo.auth.Auth#login(com.techq.weibo.robot.CrawlRobot,
	 * java.lang.String, com.techq.weibo.meta.User)
	 */
	@Override
	public boolean login(CrawlRobot robot, String url, User user) throws ShareException {
		qparams.add(new BasicNameValuePair("username", user.getUsername()));
		qparams.add(new BasicNameValuePair("password", user.getPassword()));
		UrlEncodedFormEntity params = null;
		try {
			params = new UrlEncodedFormEntity(qparams, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			logger.error("UnsupportedEncodingException", e);
			throw new ShareException("UnsupportedEncodingException", e);
		}
		post.setEntity(params);
		try {
			StringBuilder builder = robot.execute(post);
		//	logger.debug(builder.toString());
			
			String redirectUrl = getRedirectLocation(builder.toString());
			System.out.println(redirectUrl);
			StringBuilder content = robot.get(redirectUrl);
			robot.setLastPage(content.toString());
			//System.out.println(content.toString());
		} catch (ShareException e) {
			logger.error("login fail", e);
			return false;
		}
		return true;
	}

	private String getRedirectLocation(String content) {
		String regex = "location\\.replace\\(\"(.*?)\"\\)";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(content);
 
		String location = null;
		if (matcher.find()) {
			location = matcher.group(1);
		}
 
		return location;
	}
}
